<?php

/*
 * This file is part of the Geek-Zoo Projects.
 *
 * @copyright (c) 2010 Geek-Zoo Projects More info http://www.geek-zoo.com
 * @license http://opensource.org/licenses/gpl-2.0.php The GNU General Public License
 * @author xuanyan <xuanyan@geek-zoo.com>
 *
 */

class admin_resource_model extends Model
{
    function get_count($model_name, $array)
    {
        $model_id = $this->db->getOne("SELECT id FROM model WHERE name = ?", $model_name);
        $att = $this->get_att($model_id, array_keys($array));
        $sql = "SELECT b.id, COUNT(*) AS num FROM admin_attribute_value a LEFT JOIN admin_resource b ON a.res_id = b.id WHERE 0";
        
        $num = 0;
        foreach ($array as $key => $val) {
            $sql .= " OR ( a.attribute_id = ".$att[$key]." AND a.value = '".$val."')";
            $num++;
        }
        
        $sql .= " GROUP BY a.res_id HAVING num = $num";
    
        return count($this->db->getCol($sql));
    }

    function get_list($model_name, $array, $limit = '')
    {
        $model_id = $this->db->getOne("SELECT id FROM admin_model WHERE name = ?", $model_name);
        $att = $this->get_att($model_id, array_keys($array));
        $sql = "SELECT b.*, COUNT(*) AS num FROM admin_attribute_value a LEFT JOIN admin_resource b ON a.res_id = b.id WHERE 0";
        
        $num = 0;
        foreach ($array as $key => $val) {
            $sql .= " OR ( a.attribute_id = ".$att[$key]." AND a.value = '".$val."')";
            $num++;
        }
        
        $sql .= " GROUP BY a.res_id HAVING num = $num ORDER BY b.add_time DESC $limit";
    
        return $this->db->getAll($sql);
    }

    function get_att($model_id, $array)
    {
        static $att = null;
        if ($att === null) {
            $att = $this->db->getAll("SELECT * FROM admin_attribute");
        }
        $out = array();
        foreach ($att as $key => $val) {
            if ($val['model_id'] == $model_id && in_array($val['name'], $array)) {
                $out[$val['name']] = $val['id'];
            }
        }
        return $out;
    }
}


?>